package cit.project.capeclear;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.android.dataframework.DataFramework;
import com.android.dataframework.Entity;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalAdvancedPayment;

public class ShopActivity extends Activity {

	private Vector<String> categories = new Vector<String>();
	private final Vector<Item> items = new Vector<Item>();
	private Vector<Item> cItems = new Vector<Item>(); //Vector with the items checked
	private int i = 0;
	private AlertDialog  info;
	private Vector<TextView> vQty = new Vector<TextView>();
	private float total=0.0f;
	private Vector<TableRow> vRows = new Vector<TableRow>();
	private TextView totalView;
	private Map<String,String> shopMap = new HashMap<String,String>();
	private Payment payment = null;
	private CheckoutButton launchPayment = null;
	private static final int request = 1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shoplayout);

		// Opening DataBase to work hola3
		try {
			DataFramework.getInstance().open(this, "cit.project.capeclear");
		} catch (Exception e) {
			e.printStackTrace();
		}

		//Fill the shop with the categories and items of the DB
		setCategories();
		setShops();

		totalView = (TextView)this.findViewById(R.id.totalshop);
		
		// Initialize the PayPal library. We'll do it in a separate thread 
        // because it requires communication with the server
		// which may take some time depending on the connection strength/speed.
		Thread libraryInitializationThread = new Thread() {
			public void run() {
				
				payment = new Payment(ShopActivity.this);
				payment.initLibrary();
				
								
				// The library is initialized so let's create our CheckoutButton and update the UI.
				if (payment.isLibraryInitialized()) {
					
					launchPayment = payment.setupButton();
			        runOnUiThread( new Runnable()
			        {
			            @Override
			            public void run()
			            {
			            	findViewById(R.id.ppButtonLoad).setVisibility(View.GONE);
			                ((LinearLayout)findViewById(R.id.linearLayoutBottomShop)).addView(launchPayment);
			            }
			        } );

					launchPayment.setOnClickListener(paypalListener);
				}
				else
				{
			        runOnUiThread( new Runnable()
			        {
			            @Override
			            public void run()
			            {
			        		findViewById(R.id.ppButtonLoad).setVisibility(View.GONE);
			            }
			        } );
					
				}
			}
		};
		libraryInitializationThread.start();
		
	}
	


	private void setCategories(){

		//Filling up the Vector categories with the categories of the dataBase
		Entity ent = null;
		List<Entity> serviceList = DataFramework.getInstance().getEntityList("SHOP");
		Iterator<Entity> iter = serviceList.iterator();
		while (iter.hasNext()) {
			ent = (Entity)iter.next();
			//Make sure that each category is only added one time in the vector
			if(!categories.contains(ent.getString("S_CATEGORY")))
				categories.add(ent.getString("S_CATEGORY"));
		}
		
		
		//Filling the items inside each cateogry
		for(int i =0; i<categories.size(); i++){
			//Setting the categoryRow and the CategoryInfo
			TableLayout table = (TableLayout) findViewById(R.id.tableItems);
			TextView txt = (TextView) getLayoutInflater().inflate(R.layout.categoryrow, null);
			txt.setText(categories.elementAt(i));
			table.addView(txt);
			TableRow row = (TableRow) getLayoutInflater().inflate(R.layout.shoprowinfo, null);
			table.addView(row);
			
			//Function to show all the items inside each category
			if(categories.elementAt(i).equals("Combo"))
				setItemCombo();
			else
				setItem(categories.elementAt(i));
		}

	}

	private void setItemCombo() {
		
		Vector<Integer> COMBOS = new Vector<Integer>();
		
		
		
		TableLayout table = (TableLayout) findViewById(R.id.tableItems);
		TableRow row; //row for the item
		LinearLayout row2; //row for the divider
		
		Item item;
		Entity ent = null;
		List<Entity> serviceList = DataFramework.getInstance().getEntityList("SHOP", "S_CATEGORY = 'Combo'");
		Iterator<Entity> iter = serviceList.iterator();
	
		while (iter.hasNext()) {
			ent = (Entity)iter.next();
			item = new Item(ent.getInt("CODE"), ent.getString("TITLE"), ent.getString("DESCRIPTION"),
					ent.getString("S_CATEGORY"), ent.getFloat("PRICE"), ent.getInt("SHIPMENT"), ent.getString("SHOP_NAME"));
			items.add(item);
			Log.v("SHOP", "Metido elemento en el array con titulo:" + item.title + "Y codigo: " + item.code);
			
			if(!COMBOS.contains(item.code)){
				//Taking the layout of the two rows to inserts
				row = (TableRow) getLayoutInflater().inflate(R.layout.rowitem, null);
				row.setId(i);
				vRows.add(row);
				row2 = (LinearLayout) getLayoutInflater().inflate(R.layout.rowdivider, null);

				//Handle possible error Category without title in the DB
				TextView txt =((TextView)row.getChildAt(1)); 
				if(!(item.title).equals("")) 
					txt.setText(item.description);
				else{
					txt.setText("DB Error: Category without title");
				}

				//Setting up the price
				LinearLayout priceLayout =(LinearLayout)row.getChildAt(3);
				TextView price =(TextView)priceLayout.getChildAt(0);
				Log.v("CPRICE",ent.getString("C_PRICE"));
				price.setText(ent.getFloat("C_PRICE")+"");


				//Setting up the ImageViews and qty textView
				LinearLayout linear2 = (LinearLayout)row.getChildAt(2);

				ImageView more = (ImageView)linear2.getChildAt(0);
				ImageView less = (ImageView)linear2.getChildAt(2);
				TextView qty =((TextView)linear2.getChildAt(1)); 
				more.setId(i);
				less.setId(i);
				qty.setId(i);
				vQty.add(qty);
				more.setOnClickListener(imageViewListenerMore);
				less.setOnClickListener(imageViewListenerLess);


				//Setting up the textViews
				txt.setId(i);
				txt.setOnClickListener(textViewListener);

				//Setting up the checkboxs 
				CheckBox checkBox = (CheckBox)row.getChildAt(0);
				checkBox.setId(i);
				checkBox.setOnClickListener(checkListener);
				i++;

				//Adding the two rows
				table.addView(row);
				table.addView(row2);
				
				//
				COMBOS.add(item.code);
				
			}
			
			
		
		}
		
	}




	//Set all the items of the category
	private void setItem(String category){

		
		TableLayout table = (TableLayout) findViewById(R.id.tableItems);
		TableRow row; //row for the item
		LinearLayout row2; //row for the divider
		
		
		Item item;
		Entity ent = null;
		List<Entity> serviceList = DataFramework.getInstance().getEntityList("SHOP", "S_CATEGORY = '" + category +"'");
		Iterator<Entity> iter = serviceList.iterator();
		while (iter.hasNext()) {
			ent = (Entity)iter.next();
			item = new Item(ent.getInt("CODE"), ent.getString("TITLE"), ent.getString("DESCRIPTION"),
					ent.getString("S_CATEGORY"), ent.getFloat("PRICE"), ent.getInt("SHIPMENT"), ent.getString("SHOP_NAME"));
			items.add(item);
			
			//Taking the layout of the two rows to inserts
			row = (TableRow) getLayoutInflater().inflate(R.layout.rowitem, null);
			row.setId(i);
			vRows.add(row);
			row2 = (LinearLayout) getLayoutInflater().inflate(R.layout.rowdivider, null);
			
			//Handle possible error Category without title in the DB
			TextView txt =((TextView)row.getChildAt(1)); 
			if(!(item.title).equals("")) 
				txt.setText(item.title);
			else{
				txt.setText("DB Error: Category without title");
			}
			
			//Setting up the price
			LinearLayout priceLayout =(LinearLayout)row.getChildAt(3);
			TextView price =(TextView)priceLayout.getChildAt(0);
			price.setText(item.price.toString());
			
			
			//Setting up the ImageViews and qty textView
			LinearLayout linear2 = (LinearLayout)row.getChildAt(2);

			ImageView more = (ImageView)linear2.getChildAt(0);
			ImageView less = (ImageView)linear2.getChildAt(2);
			TextView qty =((TextView)linear2.getChildAt(1)); 
			more.setId(i);
			less.setId(i);
			qty.setId(i);
			vQty.add(qty);
			more.setOnClickListener(imageViewListenerMore);
			less.setOnClickListener(imageViewListenerLess);

			
			//Setting up the textViews
			txt.setId(i);
			txt.setOnClickListener(textViewListener);
			
			//Setting up the checkboxs 
			CheckBox checkBox = (CheckBox)row.getChildAt(0);
			checkBox.setId(i);
			checkBox.setOnClickListener(checkListener);
			i++;
			
			//Adding the two rows
			table.addView(row);
			table.addView(row2);			
		}
		
	}
	
	
	  
	private OnClickListener textViewListener = new OnClickListener(){ 
		public void onClick(View v){ 
			
			Item aux;
			aux = items.elementAt(v.getId());
			String ship;
			if(aux.shipment==1)
				ship="Yes";
			else
				ship="No";
			info = new AlertDialog.Builder(ShopActivity.this)
			.setTitle("Item Info")
			.setMessage("-Code: "+aux.code+"\n-Title: "+aux.title+"\n-Description: "+aux.description+
					"\n-Price: "+aux.price+"\n-Quantity: "+ aux.quantity+"\n-Shipment: "+ ship +"\n-Shop: "+aux.shopName)   
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					
				}
			})
			.create();
			info.show();
			
			
		} 
	};
	
	
	private OnClickListener checkListener = new OnClickListener(){ 
		public void onClick(View v){ 
			//Depending if check button is checked or not, attribute checked in the items vector
			//will be changed
			Item item;
			
			//Is checked
			if (((CheckBox) v).isChecked()){
				//Checked and combo
				if(items.elementAt(v.getId()).category.equals("Combo")){
					
					for(int i=0; i<items.size(); i++){
						item=items.elementAt(i);
						Log.v("bucle", "Recorriendo codigos en el array: " + item.code );
						if(item.code==items.elementAt(v.getId()).code){
							items.elementAt(i).checked=true;
							Log.v("SHOP", "Elemento encontrado: "+ item.title);
							
							setTotal();
						}
					}
					showArray();
				}
				//Checked normal
				else{
					items.elementAt(v.getId()).checked=true;
					
					setTotal();
				}
				
				
				
			}
			//Is not checked
			else{
				//is not checked combo
				if(items.elementAt(v.getId()).category.equals("Combo")){
					if(items.elementAt(v.getId()).category.equals("Combo")){
						
						for(int i=0; i<items.size(); i++){
							item=items.elementAt(i);
							Log.v("bucle", "Recorriendo codigos en el array: " + item.code );
							if(item.code==items.elementAt(v.getId()).code){
								items.elementAt(i).checked=false;
								Log.v("SHOP", "Elemento encontrado: "+ item.title);
								
								setTotal();
							}
						}
						showArray();
					}
				}
				//is not checked normal
				else{
					items.elementAt(v.getId()).checked=false;
					
					setTotal();
				}
			}
			
		} 
	};
	
	
	private OnClickListener imageViewListenerMore = new OnClickListener(){ 
		public void onClick(View v){ 
			
			if(items.elementAt(v.getId()).category.equals("Combo")){
			
				Item item;
				
				TextView t = vQty.elementAt(v.getId());
				String aux = t.getText().toString();
				int quantity = Integer.parseInt(aux);
				quantity = quantity + 1;
				t.setText(quantity+"");	
				
				Log.v("shop", items.elementAt(v.getId()).code+"");
				for(int i=0; i<items.size(); i++){
					item=items.elementAt(i);
					if(item.code==items.elementAt(v.getId()).code){
						
						
						items.elementAt(i).quantity++;
						
						TableRow row = vRows.elementAt(v.getId());
						CheckBox checkBox = (CheckBox)row.getChildAt(0);
						if(checkBox.isChecked()){
							setTotal();
							
					}			
				}	
				}
			}
			else{
				TextView t = vQty.elementAt(v.getId());
				String aux = t.getText().toString();
				int quantity = Integer.parseInt(aux);
				quantity = quantity + 1;
				t.setText(quantity+"");	
				
				items.elementAt(v.getId()).quantity++;
				
				TableRow row = vRows.elementAt(v.getId());
				CheckBox checkBox = (CheckBox)row.getChildAt(0);
				if(checkBox.isChecked()){
					setTotal();
			}

			}
				
		} 
	};
	
	
	private OnClickListener imageViewListenerLess = new OnClickListener(){ 
		public void onClick(View v){ 
			if(items.elementAt(v.getId()).category.equals("Combo")){
				TextView t = vQty.elementAt(v.getId());
				String aux = t.getText().toString();
				int quantity = Integer.parseInt(aux);
				Item item;
				if(quantity > 1)
				{
					quantity = quantity - 1;
					t.setText(quantity+"");
					
					for(int i=0; i<items.size(); i++){
						item=items.elementAt(i);
						if(item.code==items.elementAt(v.getId()).code){
							
							
							items.elementAt(i).quantity--;
							
							TableRow row = vRows.elementAt(v.getId());
							CheckBox checkBox = (CheckBox)row.getChildAt(0);
							if(checkBox.isChecked()){
								setTotal();
								
						}			
					}	
					
				
					
					}
				}
			}
			else{
				TextView t = vQty.elementAt(v.getId());
				String aux = t.getText().toString();
				int quantity = Integer.parseInt(aux);
				if(quantity > 1)
				{
					quantity = quantity - 1;
					t.setText(quantity+"");
				
					items.elementAt(v.getId()).quantity--;
					
					TableRow row = vRows.elementAt(v.getId());
					CheckBox checkBox = (CheckBox)row.getChildAt(0);
					if(checkBox.isChecked()){
						setTotal();
					}
				}
			}
		} 
	};
	
	
	
	/*In: Vector with all the items in the shop
	* Out: Vector with only the checked items 
	*/
	private Vector<Item> getItemsChecked(Vector<Item> v){
		Item item;
		cItems = new Vector<Item>();
		
		for(int i=0; i<v.size(); i++){
			item=v.elementAt(i);
			if(item.checked){
				cItems.add(item);
			}			
		}	
		return cItems;
	}
	
	
	private void setTotal(){
		
		total = 0.0f;
		for(int i=0; i<items.size(); i++){
			if(items.elementAt(i).checked){
				total=total+items.elementAt(i).quantity*items.elementAt(i).price;
			}
		}
		totalView.setText("Total: " + total + " Euros");
	}
	

	private void setShops(){
		//Filling up the HashMap with the Shop_Name - Mail of the dataBase
		Entity ent = null;
		List<Entity> serviceList = DataFramework.getInstance().getEntityList("PAYPAL");
		Iterator<Entity> iter = serviceList.iterator();
		while (iter.hasNext()) {
			ent = (Entity)iter.next();			
			shopMap.put(ent.getString("SHOP_NAME"), ent.getString("MAIL"));
		}

	}

	
    private OnClickListener paypalListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {		
			
			getItemsChecked(items);
			
			Item x;
			for(int i=0; i<cItems.size(); i++){
				x=cItems.elementAt(i);
				Log.v("x", "-Code: "+x.code+"\n-Title: "+x.title+"\n-Description: "+x.description+
						"\n-Price: "+x.price+"\n-Quantity: "+ x.quantity+"\n-Shipment: "+ x.shipment +"\n-Shop: "+x.shopName);
			}

			payment.items = getItemsChecked(items);
			payment.shopMap = shopMap;
			
			PayPalAdvancedPayment p = payment.parallelPayment();
			// Use checkout to create our Intent.
			Intent checkoutIntent = PayPal.getInstance().checkout(p, ShopActivity.this, new ResultDelegate());
			// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
			startActivityForResult(checkoutIntent, request);			
			
		}
	};

    /*
     * Executed when the PayPal activity finishes.
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode != request)
    		return;

    	/**
    	 * If you choose not to implement the PayPalResultDelegate, then you will receive the transaction results here.
    	 * Below is a section of code that is commented out. This is an example of how to get result information for
    	 * the transaction. The resultCode will tell you how the transaction ended and other information can be pulled
    	 * from the Intent using getStringExtra.
    	 */
    	switch(resultCode) {
		case Activity.RESULT_OK:
			ArrayList <Item> alItems = new ArrayList<Item>(cItems);
			Bundle bundle = new Bundle();
			bundle.putString("paymentID", data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY));
			Intent myIntent = new Intent(ShopActivity.this, PaymentResult.class);
  			myIntent.putExtras(bundle);
  			myIntent.putParcelableArrayListExtra("items", alItems);
  			ShopActivity.this.startActivity(myIntent);
			break;
/*		case Activity.RESULT_CANCELED:
			resultTitle = "CANCELED";
			resultInfo = "The transaction has been cancelled.";
			resultExtra = "";
	    	findViewById(R.id.bookLayout).setVisibility(View.GONE);
	    	findViewById(R.id.bookResultLayout).setVisibility(View.VISIBLE);
			break;
		case PayPalActivity.RESULT_FAILURE:
			resultTitle = "FAILURE";
			resultInfo = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
			resultExtra = "Error ID: " + data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
	    	findViewById(R.id.bookLayout).setVisibility(View.GONE);
	    	findViewById(R.id.bookResultLayout).setVisibility(View.VISIBLE); */
		}

    	
    	
    	launchPayment.updateButton();
    }    

	
	private void showArray(){
		for(int i=0; i<items.size(); i++){
			Log.v("items.elementAt(i)", "-Code: "+items.elementAt(i).code+"\n-Title: "+items.elementAt(i).title+"\n-Description: "+items.elementAt(i).description+
					"\n-Price: "+items.elementAt(i).price+"\n-Quantity: "+ items.elementAt(i).quantity+"\n-Shipment: "+ items.elementAt(i).shipment +"\n-Shop: "+items.elementAt(i).shopName
					+ "\nChecked: "+  items.elementAt(i).checked+"\n ");
		}
	}

}
